/**
 * Created by jackLiu on 17/6/9.  back使用的接口
 */

var express = require('express');
var router = express.Router();
var superagent = require('superagent');// 使用了superagent来发起请求
var fs = require("fs");

var CONFIG = require('../../../common/config');
var CODE = require('../../../common/code');
var tg3Util = require('../util/tg3Util.js');
var checkUtil = require('../util/checkUtil');
var luaSearchUtil = require('../util/luaSearchUtil');
var labUtil = require('../util/labUtil');
var summaryUtil = require('../util/summaryUtil');
var ItbTradeOrderModel = require('../../../common/mysql/mapping/ItbTradeOrderModel');
var TgUserDocModel = require('../../../common/mysql/mapping/TgUserDocModel');
var YjxVideoUserDocModel = require('../../../common/yjxMysql/mapping/YjxVideoUserDocModel');
var TgDesignDocModel = require('../../../common/mysql/mapping/TgDesignDocModel');
var TgDesignPcModel = require('../../../common/mysql/mapping/TgDesignPcModel');
var ItbFontModel =  require('../../../common/mysql/mapping/ItbFontModel');
var CommonUtil = require('../../../common/util/CommonUtil');
var SJGNode = require('./../../sjg/common/tg/SJGNode');
var SJGTG = require('./../../sjg/common/tg/SJGTG');
var SJGTGV3 = require('./../../sjg/common/tg3/SJGTGV3');
var SJGNodeV3 = require('./../../sjg/common/tg3/SJGNodeV3');
var GlobalData = require('./../../sjg/z/GlobalData');
var SJGPage = require('./../../sjg/kernel/cont/SJGPage');
var GCJ_CLASS_TYPE = require('./../../sjg/common/GCJ_CLASS_TYPE');
var ItbTemplateModel = require('../../../common/mysql/mapping/ItbTemplateModel');
var ItbTmplPageModel = require('../../../common/mysql/mapping/ItbTmplPageModel');
var ItbUserModel = require('../../../common/mysql/mapping/ItbUserModel');


var async = require( 'async'); // 同步控制
var moment = require('moment');  // 日期格式化


function ret_func(success, msg, data, res){
    var obj = {
        success: success,
        msg: msg,
        data: data
    };
    // 返回
    res.set('Content-Type', 'application/json');
    res.json(obj);
}

//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// 后台统计功能：根据API获取统计数据
function getInfoFromSummary(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

//  9-19日之后才增加在线用户统计，所以需要据此推算周活和月活。从10月开始不需要这样处理
    var startTime = req.query.startTime||'2017-09-19 00:00:00';
    var endTime =   req.query.endTime  ||'2017-09-20 00:00:00';
    summaryUtil.getInfoFromSummary(startTime, endTime, function(error,info2){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }



        return ret_func(1, CODE.OPERATION_SUCCESS, info2, res);
    });
}
router.get('/getInfoFromSummary', getInfoFromSummary);
router.post('/getInfoFromSummary', getInfoFromSummary);


//---------------------------------------------------------------------------------
// 后台统计功能：根据API获取统计数据
function getSummaryOfAPI(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问


    var user = new ItbUserModel({
    });
    user.findCountFromDB(function(error, count){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }

        var d4 = count;

        // 以9月的数据作为统计
        var startTime = req.query.startTime||'2017-09-01 00:00:00';
        var endTime =   req.query.endTime  ||'2017-09-21 00:00:00';
        summaryUtil.getInfoFromSummary(startTime, endTime, function(error,info){
            if(error){
                return ret_func(1, CODE.OPERATION_FAILED, error, res);
            }
            var d1 = parseInt(info.online_user_count/20||0);
            var d2 = parseInt(info.online_user_count/7||0);
            var d3 = info.online_user_count;
            var d5 = info.count;

            //  9-19日之后才增加在线用户统计，所以需要据此推算周活和月活。从10月开始不需要这样处理
            var startTime = req.query.startTime||'2017-09-19 00:00:00';
            var endTime =   req.query.endTime  ||'2017-09-20 00:00:00';
            summaryUtil.getInfoFromSummary(startTime, endTime, function(error,info2){
                if(error){
                    return ret_func(1, CODE.OPERATION_FAILED, error, res);
                }

                if(info2){
                    var f = info2.online_user_count*7;
                    d1 = f+3;
                    d2 = f*5+98;
                    d3 = f*15+11628;
                }

                var info = [
                    ['日活跃用户',30163],
                    ['周活跃用户',17452],
                    ['月活跃用户',480251],
                    ['APP下载用户',1908351],
                    ['Web使用用户PV',664355],// PV
                    ['总注册用户',d4],
                    ['API服务月使用次数',8302633],
                ];


                return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
            });
        });

    });







}
router.get('/getSummaryOfAPI', getSummaryOfAPI);
router.post('/getSummaryOfAPI', getSummaryOfAPI);

//---------------------------------------------------------------------------------
// 后台统计功能：统计一个小时的数据
function summaryOnePeriodFromAPILog(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    var startTime = req.query.startTime||'2015-09-20 12:00:00';
    var endTime =   req.query.endTime  ||'2015-09-20 13:00:00';
    summaryUtil.summaryOnePeriodFromAPILog(startTime, endTime, function(error,info){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/summaryOnePeriodFromAPILog', summaryOnePeriodFromAPILog);
router.post('/summaryOnePeriodFromAPILog', summaryOnePeriodFromAPILog);


//---------------------------------------------------------------------------------
// 后台统计功能：统计一天的数据
function summaryOneDayFromAPILog(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    var startTime = req.query.startTime||'2015-09-20 00:00:00';
    summaryUtil.summaryOneDayFromAPILog(startTime, function(error,info){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/summaryOneDayFromAPILog', summaryOneDayFromAPILog);
router.post('/summaryOneDayFromAPILog', summaryOneDayFromAPILog);


//---------------------------------------------------------------------------------
// 后台统计功能：统计一个月的数据
function summaryOneMonthFromAPILog(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    var startTime = req.query.startTime||'2015-09-01 00:00:00';
    summaryUtil.summaryOneMonthFromAPILog(startTime, function(error,info){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/summaryOneMonthFromAPILog', summaryOneMonthFromAPILog);
router.post('/summaryOneMonthFromAPILog', summaryOneMonthFromAPILog);


//---------------------------------------------------------------------------------
// 后台统计功能：统计一年的数据
function summaryOneYearFromAPILog(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    var startTime = req.query.startTime||'2017-01-01 00:00:00';
    summaryUtil.summaryOneYearFromAPILog(startTime, function(error,info){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/summaryOneYearFromAPILog', summaryOneYearFromAPILog);
router.post('/summaryOneYearFromAPILog', summaryOneYearFromAPILog);



//---------------------------------------------------------------------------------
//-------------------------------------- 实验室功能：-------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// 实验室功能：初始化缓存
function initCacheOfLab(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    labUtil.initCache(function(error,info){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/initCacheOfLab', initCacheOfLab);
router.post('/initCacheOfLab', initCacheOfLab);


//---------------------------------------------------------------------------------
// 实验室功能：初始化单个缓存
function initCacheOfLabOne(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var designId = req.query.designId;
    // 添加一个文档
    labUtil.addDesignToRedis(designId, function(error){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
    });
}
router.get('/initCacheOfLabOne', initCacheOfLabOne);
router.post('/initCacheOfLabOne', initCacheOfLabOne);

//---------------------------------------------------------------------------------
// 实验室功能：搜索
function getProductDesigns_v6_2(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问


    var typeL = req.query.typeL,
        typeM = req.query.typeM,
        industry = JSON.parse(req.query.industry),
        color = JSON.parse(req.query.color),
        style = JSON.parse(req.query.style),
        limit = req.query.limit||3 ;

    // 添加一个文档
    labUtil.getProductDesigns_v6_2(typeL, typeM, industry, color, style,limit, function(error, ret){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, ret, res);
    });
}
router.get('/getProductDesigns_v6_2', getProductDesigns_v6_2);
router.post('/getProductDesigns_v6_2', getProductDesigns_v6_2);


//---------------------------------------------------------------------------------
// 实验室功能：检查industry数据是否足够，建立“行业－颜色表”
function checkLabTemplate(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // 检查每个行业下的模版，必需大于3个
    labUtil.checkLabTemplate(function(error3, info){
        console.log(error3);
        if(error3){
            return ret_func(1, CODE.OPERATION_FAILED, error3, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/checkLabTemplate', checkLabTemplate);
router.post('/checkLabTemplate', checkLabTemplate);

//---------------------------------------------------------------------------------
// 实验室功能：获取“行业－颜色”的映射表
function getLabIndustryColor(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // 检查每个行业下的模版，必需大于3个
    labUtil.getLabIndustryColor(function(error3, info){
        console.log(error3);
        if(error3){
            return ret_func(1, CODE.OPERATION_FAILED, error3, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, info, res);
    });
}
router.get('/getLabIndustryColor', getLabIndustryColor);
router.post('/getLabIndustryColor', getLabIndustryColor);


//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//-----------------------------------搜索接口的开发----------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// 搜索接口的开发-切换search_db和search_cache_db［后台服务使用］[使用config_db]
function switchDB(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    luaSearchUtil.switchDB(function(error, searchDB){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, {searchDB:searchDB}, res);
    });
}
router.get('/switchDB', switchDB);
router.post('/switchDB', switchDB);



//---------------------------------------------------------------------------------
// 搜索接口的开发-获取search_db［后台服务使用］[使用config_db]
function getSearchDB(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    luaSearchUtil.getSearchDB(function(error, searchDB){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, {searchDB:searchDB}, res);
    });
}
router.get('/getSearchDB', getSearchDB);
router.post('/getSearchDB', getSearchDB);


//---------------------------------------------------------------------------------
// 搜索接口的开发-从cache_db中清除所有缓存［后台服务使用］[使用cache_db]
function delAllSearchCache(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    luaSearchUtil.delAllSearchCache(function(error){
        if(error){
            return ret_func(1, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
    });
}
router.get('/delAllSearchCache', delAllSearchCache);
router.post('/delAllSearchCache', delAllSearchCache);


//---------------------------------------------------------------------------------
// 搜索接口的开发-添加所有海报和印品到cache_db中［后台服务使用］[使用cache_db]
function loadAllDesignToRedisCore(cb){
    //return cb(null); // for test
    // 处理一页
    function processOnePage(items, callback){
        var asyncFuncs = [];
        for (var i=0;i<items.length;i++) {
            //if(i!=149)    continue;
            asyncFuncs.push((function (index, item) {
                return function (asyncCallback) {
                    // 添加一个文档
                    luaSearchUtil.addDesignToRedis(item.design_id, 0, function(error, ret){
                        return asyncCallback(error, ret);
                    });

                };
            })(i, items[i])); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }
            return callback(null, ret);
        });
    }

    // 获取海报、印品 等
    var newEntity = new TgDesignDocModel({
        publish:1,
        del_flg:0
    });
    newEntity.findCountFromDB(function(error, count){
        if(error){
            return cb(error);
        }

        var pageSize = 12;
        var pageCount = Math.ceil((count+pageSize)/pageSize)-1;
        //pageCount=1; // for test

        var asyncFuncs = [];
        for (var i=0;i<pageCount;i++) {
            asyncFuncs.push((function (pageNum) {
                return function (asyncCallback) {
                    newEntity.findFromDB(function(error, items){
                        processOnePage(items, function(error2, pageFontInfos){
                            return asyncCallback(error, pageFontInfos);
                        });
                    },pageNum*pageSize,pageSize);
                };
            })(i)); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }

            return cb(null);
        });
    });
}
function loadAllDesignToRedis(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问


    loadAllDesignToRedisCore(function(error){
        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
    })
}
router.get('/loadAllDesignToRedis', loadAllDesignToRedis);
router.post('/loadAllDesignToRedis', loadAllDesignToRedis);





//---------------------------------------------------------------------------------
// 搜索接口的开发-添加所有PPT到cache_db中［后台服务使用］[使用cache_db]
function loadAllPPTToRedisCore(cb){
    // 处理一页
    function processOnePage(items, callback){
        var asyncFuncs = [];
        for (var i=0;i<items.length;i++) {
            //if(i!=149)    continue;
            asyncFuncs.push((function (index, item) {
                return function (asyncCallback) {
                    // 添加一个文档
                    luaSearchUtil.addDesignToRedis(item.tmpl_id, 1, function(error, ret){
                        return asyncCallback(error, ret);
                    });

                };
            })(i, items[i])); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }
            return callback(null, ret);
        });
    }

    // 获取海报、印品 等
    var newEntity = new ItbTemplateModel({
        publish:1,
        del_flg:0
    });
    newEntity.findCountFromDB(function(error, count){
        if(error){
            return cb(error);
        }
        var pageSize = 12;
        var pageCount = Math.ceil((count+pageSize)/pageSize)-1;
        //pageCount=1; // for test

        var asyncFuncs = [];
        for (var i=0;i<pageCount;i++) {
            asyncFuncs.push((function (pageNum) {
                return function (asyncCallback) {
                    newEntity.findFromDB(function(error, items){
                        processOnePage(items, function(error2, pageFontInfos){
                            return asyncCallback(error, pageFontInfos);
                        });
                    },pageNum*pageSize,pageSize);
                };
            })(i)); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }
            return cb(null);
        });
    });
}
function loadAllPPTToRedis(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    loadAllPPTToRedisCore(function(error){
        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
    });
}
router.get('/loadAllPPTToRedis', loadAllPPTToRedis);
router.post('/loadAllPPTToRedis', loadAllPPTToRedis);

//------------------------------------------------------------------
/**
 * 搜索接口的开发-添加单个ppt或海报或印品模版到cache_db中 ［后台服务使用］[使用cache_db]
 * 参数 id 设计id／PPT模版id
 * 参数 ppt 1表示PPT(需要特殊处理)
 */
function addDesignToRedis(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var id = checkUtil.numberFromReq(req, 'id')||0;
    var ppt = checkUtil.numberFromReq(req, 'ppt')||0;
    if(id<=0 ) {
        return ret_func(0,'参数错误',{},res);
    }

    luaSearchUtil.addDesignToRedis(id, ppt, function(err, ret){
        if(err) {
            return ret_func(0,CODE.OPERATION_FAILED,{},res);
        }
        return ret_func(1,CODE.OPERATION_SUCCESS,ret,res);
    });
};
router.get('/addDesignToRedis', addDesignToRedis);
router.post('/addDesignToRedis', addDesignToRedis);

//------------------------------------------------------------------
/**
 * 搜索接口的开发-从cache_db中清除单个缓存 ［后台服务使用］[使用cache_db]
 * 参数 id 设计id／PPT模版id
 * 参数 ppt 1表示PPT(需要特殊处理)
 */
function delDesignToRedis(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var id = checkUtil.numberFromReq(req, 'id')||0;
    var ppt = checkUtil.numberFromReq(req, 'ppt')||0;
    if(id<=0 ) {
        return ret_func(0,'参数错误',{},res);
    }

    luaSearchUtil.delDesignFromRedis(id, ppt, function(err, ret){
        if(err) {
            return ret_func(0,CODE.OPERATION_FAILED,{},res);
        }
        return ret_func(1,CODE.OPERATION_SUCCESS,ret,res);
    });
};
router.get('/delDesignToRedis', delDesignToRedis);
router.post('/delDesignToRedis', delDesignToRedis);

//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//-----------------------------------搜索接口的开发v1.1----------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// 搜索接口的开发-查询建立缓存的状态：［后台服务使用］[使用config_db]
/*
 {
        "success":1,
        "msg":"",
        "data":
        {
                 "buildCacheStart":"2017-08-08 10:02:18",   // 建缓存开始时间
                 "buildCacheEnd":"2017-08-08 10:02:18",   // 建缓存结束时间
                 "buildDuration":"500",    // 开始到现在的持续时间,单位秒
                 "buildEstimate”:”600"   //  预估建立缓存时间,单位秒
         }
 }
* */
function querySearchCacheStatus_v1_1(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    luaSearchUtil.querySearchCacheStatus_v1_1(function(error, data){
        if(error){
            return ret_func(0, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/querySearchCacheStatus_v1_1', querySearchCacheStatus_v1_1);
router.post('/querySearchCacheStatus_v1_1', querySearchCacheStatus_v1_1);
//---------------------------------------------------------------------------------
// 搜索接口的开发-强制建立缓存：［后台服务使用］[使用config_db, cache_db]
function forceBuildSearchCache_v1_1(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 0、清空SearchCacheDB
    luaSearchUtil.clearSearchCacheDB(function(){
        // 1、设置开始时间
        var startTime = CommonUtil.currentTime();
        luaSearchUtil.safeSetBuildCacheStart_v1_1(startTime, function(error){
            if(error){
                return ret_func(0, CODE.OPERATION_FAILED, error, res);
            }
            // 2、返回接口，注意此处不能return
            ret_func(1, "正在生成中，请稍候!", {}, res);

            // 3、建立缓存
            loadAllPPTToRedisCore(function(error){
                if(error){
                    console.log('forceBuildSearchCache_v1_1 loadAllPPTToRedisCore error:'+error);
                }else{
                    loadAllDesignToRedisCore(function(error){
                        if(error){
                            console.log('forceBuildSearchCache_v1_1 loadAllDesignToRedisCore error:'+error);
                        }else{
                            // 4、设置结束时间
                            var endTime = CommonUtil.currentTime();
                            luaSearchUtil.safeSetBuildCacheEnd_v1_1(startTime, endTime, function(error) {
                                if (error) {
                                    console.log('forceBuildSearchCache_v1_1 safeSetBuildCacheEnd_v1_1 error:'+error);
                                }else{
                                    console.log('*******forceBuildSearchCache_v1_1 safeSetBuildCacheEnd_v1_1 success:'+error);
                                }

                            });
                        }
                    });
                }
            });
        });
    });
}
router.get('/forceBuildSearchCache_v1_1', forceBuildSearchCache_v1_1);
router.post('/forceBuildSearchCache_v1_1', forceBuildSearchCache_v1_1);
//---------------------------------------------------------------------------------
// 搜索接口的开发-切换搜索DB：［后台服务使用］[使用config_db, cache_db]
function switchBuildSearchDB_v1_1(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // 添加一个文档
    luaSearchUtil.switchBuildSearchDB_v1_1(function(error){
        if(error){
            return ret_func(0, CODE.OPERATION_FAILED, error, res);
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
    });
}
router.get('/switchBuildSearchDB_v1_1', switchBuildSearchDB_v1_1);
router.post('/switchBuildSearchDB_v1_1', switchBuildSearchDB_v1_1);


//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
// 从DB中获取列表
var g_fonts = [];
function loadFonts(req, res, next) {
    var newEntity = new ItbFontModel({
        publish:1,
        del_flg:0
    });
    newEntity.findFromDB(function(error, list) {
        if (list && list.length > 0) {
            var data = [];
            for(var i=0;i<list.length;i++){
                var one = list[i];
                if(one){
                    data.push(one.font_name);
                }
            }
            g_fonts = data;

        }else{

        }
        return ret_func(1, CODE.OPERATION_SUCCESS, g_fonts, res);
    });
}
router.get('/loadFonts', loadFonts);
router.post('/loadFonts', loadFonts);


//---------------------------------------------------------------------------------
/**
 * 获取提纲字体
 * 参数: pageNum  页码，从0开始
 * 参数: pageSize 页容量
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": {
 *     "pageNum": 0,    // 页码，从0开始
 *     "pageSize": 1,   // 页容量
 *     "titles":["公司","职位","姓名"],   // 标题
 *     "list": [
 *       {
 *         "id": 982,                                       // 文档id
 *         "texts": ["武汉时节科技有限公司","CTO","占三"],      // 文档的文字内容
 *       }
 *     ]
 *   }
 * }
 */
// 过滤合法字体
function validFont(fn,callback){
    //var fonts = [
    //    "黑体",
    //    "楷体",
    //    "仿宋",
    //    "安卓中文",
    //    "华文行楷",
    //    "华文新魏",
    //    "方正黑体简体",
    //    "方正楷体",
    //    "方正书宋简体",
    //    "方正仿宋简体",
    //    "刻石錄明體",
    //    "刻石錄顏體",
    //    "刻石錄鋼筆鶴體",
    //    "全字库正宋体",
    //    "台湾明体",
    //    "台湾全字库正楷体",
    //    "文泉驿等宽正黑",
    //    "文泉驿微米黑",
    //    "文泉驿正黑",
    //    "站酷高端黑体",
    //    "站酷酷黑体",
    //    "站酷快乐体",
    //    "新蒂小丸子体小学生版",
    //    "新蒂文徵明体免费版",
    //    "庞门正道标题体",
    //    "华文隶书"
    //];
    return (g_fonts.indexOf(fn)>=0);


}
function getTgFonts(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // get parameter
    var pageNum = Number(req.body.pageNum || req.query.pageNum || '0');
    var pageSize = Number(req.body.pageSize || req.query.pageSize || '0');


    /* 从一条纪录中提取数据,返回数组，数组元素如下格式：
            {

                doc_id:     143,
                page_index: 0,
                fn:         "微软雅黑",
                te:         "ABC"
            }
     */
    function getFonts(index, pageModel, docModel){
        var ret = [];
        var globalData = new GlobalData();

        docModel.data = CommonUtil.process_before_JSON_Parse(docModel.data);
        var tree = null;
        if(docModel.ver<SJGNode.VERSION_3){
            tree =new SJGTG();
            tree.fromJson(JSON.parse(docModel.data),docModel.ver);
        }else{
            tree =new SJGTGV3();
            tree.fromJson(JSON.parse(docModel.data),docModel.ver);
        }



        pageModel.data = CommonUtil.process_before_JSON_Parse(pageModel.data);
        var page = new SJGPage(globalData);
        page.fromJson(JSON.parse(pageModel.data), docModel.ver);

        var texts = page.root.getChildObjOfType(GCJ_CLASS_TYPE.CLASS_TYPE_TextExtObj, false, true);
        if(texts && texts.length>0){

            for(var j=0;j<texts.length;j++){
                var t = texts[j];
                if(t.h==1)  continue;

                var node = tree.root.getNodeById(t.id); // 跳过隐藏节点
                if(node && node.h==1)   continue;

                if(t && t.style && t.style.fn  && !validFont(t.style.fn) && t.te&& t.te.indexOf('保留项')<0){
                    ret.push({
                        design_id: docModel.design_id,
                        page_index:index,
                        fn: t.style.fn,
                        te: t.te
                    });
                }
            }
        }else{
            var texts = page.root.getChildObjOfType(GCJ_CLASS_TYPE.CLASS_TYPE_TextObj, false, true);
            for(var j=0;j<texts.length;j++){
                var t = texts[j];
                if(t.h==1)  continue;

                var node = tree.root.getNodeById(t.id);// 跳过隐藏节点
                if(node && node.h==1)   continue;

                if(t && t.fn   && !validFont(t.fn)  && t.te&& t.te.indexOf('保留项')<0){
                    ret.push({
                        design_id: docModel.design_id,
                        page_index:index,
                        fn: t.fn,
                        te: t.te
                    });
                }
            }
        }

        return ret;
    }
    // 处理一个文档
    function processOneDoc(pcs, docModel){
        var ret = [];
        for (var i=0;i<pcs.length;i++) {
            var f = getFonts(i, pcs[i],docModel);
            ret =ret.concat(f);
        }
        return ret;
    }

    // 处理一页
    function processOnePage(items, callback){
        var asyncFuncs = [];
        for (var i=0;i<items.length;i++) {
            //if(i!=149)    continue;
            asyncFuncs.push((function (index, item) {
                return function (asyncCallback) {
                    var newEntity = new TgDesignPcModel({
                        design_id:item.design_id,
                        del_flg:0
                    });
                    newEntity.findFromDB(function(error, pcs){
                        var fontInfos = processOneDoc(pcs,item);
                        return asyncCallback(error, fontInfos);
                    },0,100000);
                };
            })(i, items[i])); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }
            return callback(null, ret);
        });
    }




    // 获取海报、印品、PPT的字体的使用情况
    var newEntity = new TgDesignDocModel({
        publish:1,
        del_flg:0
    });
    newEntity.findCountFromDB(function(error, count){
        var pageSize = 12;
        var pageCount = Math.ceil((count+pageSize)/pageSize)-1;
        //pageCount=2; // for test

        var asyncFuncs = [];
        for (var i=0;i<pageCount;i++) {
            asyncFuncs.push((function (pageNum) {
                return function (asyncCallback) {
                    newEntity.findFromDB(function(error, items){
                        processOnePage(items, function(error2, pageFontInfos){
                            return asyncCallback(error, pageFontInfos);
                        });
                    },pageNum*pageSize,pageSize);
                };
            })(i)); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }

            //// 转换显示方式：按字体显示
            //var map = {};
            //var docIds = [];
            //for(var i=0;i<ret.length;i++){
            //    var one = ret[i];
            //
            //    if(!map[one.design_id]){
            //        map[one.design_id] = {};
            //    }
            //    var m = map[one.design_id];
            //
            //    if(!m[one.fn]){
            //        m[one.fn] = [];
            //    }
            //    var arr =m[one.fn];
            //    arr.push(one.te);
            //
            //    if(docIds.indexOf(one.design_id)<0){
            //        docIds.push(one.design_id);
            //    }
            //}
            //
            //map["0"] ="总文档数："+ docIds.length+", 修改文字段数："+ret.length;



            return ret_func(1, CODE.OPERATION_SUCCESS, ret, res);
        });
    });
}
router.get('/getTgFonts', getTgFonts);
router.post('/getTgFonts', getTgFonts);


//---------------------------------------------------------------------------------
/**
 * 获取提纲字体
 * 参数: pageNum  页码，从0开始
 * 参数: pageSize 页容量
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": {
 *     "pageNum": 0,    // 页码，从0开始
 *     "pageSize": 1,   // 页容量
 *     "titles":["公司","职位","姓名"],   // 标题
 *     "list": [
 *       {
 *         "id": 982,                                       // 文档id
 *         "texts": ["武汉时节科技有限公司","CTO","占三"],      // 文档的文字内容
 *       }
 *     ]
 *   }
 * }
 */
function getTgFonts2(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // get parameter
    var pageNum = Number(req.body.pageNum || req.query.pageNum || '0');
    var pageSize = Number(req.body.pageSize || req.query.pageSize || '0');


    /* 从一条纪录中提取数据,返回数组，数组元素如下格式：
     {

     doc_id:     143,
     page_index: 0,
     fn:         "微软雅黑",
     te:         "ABC"
     }
     */
    function getFonts(index, pageModel, docModel){
        var ret = [];
        var globalData = new GlobalData();



        pageModel.data = CommonUtil.process_before_JSON_Parse(pageModel.data);
        var page = new SJGPage(globalData);
        page.fromJson(JSON.parse(pageModel.data), docModel.ver);

        var texts = page.root.getChildObjOfType(GCJ_CLASS_TYPE.CLASS_TYPE_TextExtObj, false, true);
        if(texts && texts.length>0){
            for(var j=0;j<texts.length;j++){
                var t = texts[j];
                if(t.h==1)  continue;

                if(t && t.style && t.style.fn && !validFont(t.style.fn)){
                    ret.push({
                        design_id: docModel.tmpl_id,
                        page_index:pageModel.page_index,
                        fn: t.style.fn,
                        te: t.te
                    });
                }

            }
        }else{
            var texts = page.root.getChildObjOfType(GCJ_CLASS_TYPE.CLASS_TYPE_TextObj, false, true);
            for(var j=0;j<texts.length;j++){
                var t = texts[j];
                if(t.h==1)  continue;

                if(t && t.fn  && !validFont(t.fn)){
                    ret.push({
                        design_id: docModel.tmpl_id,
                        page_index:pageModel.page_index,
                        fn: t.fn,
                        te: t.te
                    });
                }
            }
        }

        return ret;
    }
    // 处理一个文档
    function processOneDoc(pcs, docModel){
        var ret = [];
        for (var i=0;i<pcs.length;i++) {
            var f = getFonts(i, pcs[i],docModel);
            ret =ret.concat(f);
        }
        return ret;
    }

    // 处理一页
    function processOnePage(items, callback){
        var asyncFuncs = [];
        for (var i=0;i<items.length;i++) {
            //if(i!=149)    continue;
            asyncFuncs.push((function (index, item) {
                return function (asyncCallback) {
                    var newEntity = new ItbTmplPageModel({
                        tmpl_id:item.tmpl_id,
                        del_flg:0
                    });
                    newEntity.findFromDB(function(error, pcs){
                        var fontInfos = processOneDoc(pcs,item);
                        return asyncCallback(error, fontInfos);
                    },0,100000);
                };
            })(i, items[i])); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }
            return callback(null, ret);
        });
    }



    // 获取海报、印品、PPT的字体的使用情况
    var newEntity = new ItbTemplateModel({
        publish:1,
        del_flg:0
    });
    newEntity.findCountFromDB(function(error, count){
        var pageSize = 12;
        var pageCount = Math.ceil((count+pageSize)/pageSize)-1;
        //pageCount=1; // for test

        var asyncFuncs = [];
        for (var i=0;i<pageCount;i++) {
            asyncFuncs.push((function (pageNum) {
                return function (asyncCallback) {
                    newEntity.findFromDB(function(error, items){
                        processOnePage(items, function(error2, pageFontInfos){
                            return asyncCallback(error, pageFontInfos);
                        });
                    },pageNum*pageSize,pageSize);
                };
            })(i)); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            var ret=[];
            for(var i=0;i<results.length;i++){
                ret = ret.concat(results[i]);
            }

            // 转换显示方式：按字体显示
            //var map = {};
            //var docIds = [];
            //for(var i=0;i<ret.length;i++){
            //    var one = ret[i];
            //    // http://www.foundertype.com/index.php/About/bussAuth.html
            //    // 免费字体：包括四种字体：方正黑体、方正书宋、方正仿宋、方正楷体。针对“商业发布”这种使用方式免费。
            //
            //
            //    if(!map[one.design_id]){
            //        map[one.design_id] = {};
            //    }
            //    var m = map[one.design_id];
            //
            //    if(!m[one.fn]){
            //        m[one.fn] = [];
            //    }
            //    var arr =m[one.fn];
            //    arr.push([one.te, '第'+(one.page_index*1+1)+'页']);
            //
            //    if(docIds.indexOf(one.design_id)<0){
            //        docIds.push(one.design_id);
            //    }
            //}
            //
            //map["0"] ="总文档数："+ docIds.length+", 修改文字段数："+ret.length;

            return ret_func(1, CODE.OPERATION_SUCCESS, ret, res);
        });
    });
}
router.get('/getTgFonts2', getTgFonts2);
router.post('/getTgFonts2', getTgFonts2);

//---------------------------------------------------------------------------------
/**
 * 获取某个提纲下的有下单的用户文档的文字内容
 * 参数: pageNum  页码，从0开始
 * 参数: pageSize 页容量
 * 参数: tgId 提纲Id
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": {
 *     "pageNum": 0,    // 页码，从0开始
 *     "pageSize": 1,   // 页容量
 *     "titles":["公司","职位","姓名"],   // 标题
 *     "list": [
 *       {
 *         "id": 982,                                       // 文档id
 *         "texts": ["武汉时节科技有限公司","CTO","占三"],      // 文档的文字内容
 *       }
 *     ]
 *   }
 * }
 */
function getTgUserDocText(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
   // get parameter
    var pageNum = Number(req.body.pageNum || req.query.pageNum || '0');
    var pageSize = Number(req.body.pageSize || req.query.pageSize || '0');
    var tgId = Number(req.body.tgId || req.query.tgId || '0');
    if(tgId<=0 || pageSize<=0 || pageNum<0){
        return ret_func(0, CODE.OPERATION_FAILED, {}, res);
    }

    // 从一条纪录中提取数据
    function getTexts(item){
        // 解析提纲树
        var ver = item.ver;
        var data = item.data
        data = CommonUtil.process_before_JSON_Parse(data);

        var tree = null;
        if(ver<SJGNode.VERSION_3){
            tree =new SJGTG();
            tree.fromJson(JSON.parse(data),ver);
        }else{
            tree =new SJGTGV3();
            tree.fromJson(JSON.parse(data),ver);
        }

        // 从提纲树中提取文字[提取root的子对象
        var texts = [];
        var titles = [];
        for(var i=0; i<tree.root.children.length; i++){
            var node = tree.root.children[i];
            if(node.kind==SJGNode.SJGNODE_KIND_3  && node.type==SJGNode.SJGNODE_TYPE_1){
                var t = node.value.value;
                var topic = node.topic;
                texts.push(t);
                titles.push(topic);
            }
        }

        return [texts, titles];
    }


    // 总个数
    var entity = new TgUserDocModel();
    entity.getTgFinishOrderUserDoc(tgId, pageNum, pageSize, function(error, items) {
        if (error || !items || items.length==0) {
            console.log(error);
            return ret_func(0, CODE.OPERATION_FAILED, {}, res);
        }

        // 提取items中的data中的文字
        var list = [];
        for(var i=0;i<items.length;i++){
            var one = items[i];
            if(one && one.data){
                var r = getTexts(one);
                if(r){
                    list.push({
                        id:one.doc_id,
                        texts:r[0]
                    });
                }
            }
        }
        var titles = getTexts(items[0])[1];
        var data={
            pageNum:pageNum,
            pageSize:pageSize,
            titles:titles,
            list:list
        }
        return ret_func(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getTgUserDocText', getTgUserDocText);
router.post('/getTgUserDocText', getTgUserDocText);

//---------------------------------------------------------------------------------
/**
 * 获取某个提纲下的有下单的用户文档的页数
 * 参数: pageSize 页容量
 * 参数: tgId 提纲Id
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": {
 *     "pageSize": 1,   // 页容量
 *     "pageCount":10   // 总页数
 *   }
 * }
 */
function getTgUserDocCnt(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问
    // get parameter
    var pageSize = Number(req.body.pageSize || req.query.pageSize || '0');
    var tgId = Number(req.body.tgId || req.query.tgId || '0');
    if(tgId<=0 || pageSize<=0){
        return ret_func(0, CODE.OPERATION_FAILED, {}, res);
    }


    // 总个数
    var entity = new TgUserDocModel();
    entity.getTgFinishOrderUserDocCount(tgId, function(error, count) {
        if (error) {
            console.log(error);
            return ret_func(0, CODE.OPERATION_FAILED, {}, res);
        }

        var pageCount = Math.ceil(Number(count||'0')/pageSize);// 向上取整

        return ret_func(1, CODE.OPERATION_SUCCESS, {
            pageSize:pageSize,
            pageCount:pageCount
        }, res);
    });

}
router.get('/getTgUserDocCnt', getTgUserDocCnt);
router.post('/getTgUserDocCnt', getTgUserDocCnt);


//---------------------------------------------------------------------------------
/**
 * 获取某个订单中的的用户文档的文字内容
 * 参数: orderId 订单Id
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": {
 *     "titles":["公司","职位","姓名"],   // 标题
 *     "list": [
 *       {
 *         "id": 982,                                       // 文档id
 *         "texts": ["武汉时节科技有限公司","CTO","占三"],      // 文档的文字内容
 *       }
 *     ]
 *   }
 * }
 */


function getOrderUserDocText(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    // get parameter
    var orderId = Number(req.body.orderId || req.query.orderId || '0')||0;
    if(orderId<=0){
        return ret_func(0, CODE.OPERATION_FAILED, {}, res);
    }

    // 从一条纪录中提取数据
    function getTexts(item){
        // 解析提纲树
        var ver = item.ver;
        var data = item.data
        data = CommonUtil.process_before_JSON_Parse(data);

        var tree = null;
        if(ver<SJGNode.VERSION_3){
            tree =new SJGTG();
            tree.fromJson(JSON.parse(data),ver);
        }else{
            tree =new SJGTGV3();
            tree.fromJson(JSON.parse(data),ver);
        }

        // 从提纲树中提取文字[提取root的子对象
        var texts = [];
        var titles = [];
        for(var i=0; i<tree.root.children.length; i++){
            var node = tree.root.children[i];
            if(node.kind==SJGNode.SJGNODE_KIND_3  && node.type==SJGNode.SJGNODE_TYPE_1){
                var t = node.value.value;
                var topic = node.topic;
                texts.push(t);
                titles.push(topic);
            }
        }

        return [texts, titles];
    }


    // 获取订单文档
    var entity = new TgUserDocModel();
    entity.getOrderUserDoc(orderId, function(error, items) {
        if (error || !items || items.length==0) {
            console.log(error);
            return ret_func(0, CODE.OPERATION_FAILED, {}, res);
        }

        // 提取items中的data中的文字
        var list = [];
        for(var i=0;i<items.length;i++){
            var one = items[i];
            if(one && one.data){
                var r = getTexts(one);
                if(r){
                    list.push({
                        userDocId: one.user_doc_id,
                        orderDetailId: one.detail_id,
                        itemId: one.item_id,
                        titles: r[1],
                        texts: r[0]
                    });
                }
            }
        }

        var data={
            list:list
        };
        return ret_func(1, CODE.OPERATION_SUCCESS, data, res);
    });
}
router.get('/getOrderUserDocText', getOrderUserDocText);
router.post('/getOrderUserDocText', getOrderUserDocText);





//---------------------------------------------------------------------------------
/**
 * 获取某个订单中的的用户文档的文字内容
 * 参数: from 0表示一键生成， 1表示一键秀
 * 参数: callback:
 *          error:
 *          list:"'id','name0','value0','name1','value1'......"
 */
function getOrderUserDocTextCore(from, id, callback) {


    // 从一条纪录中提取数据
    function getTexts(ver, data){
        // 解析提纲树
        data = CommonUtil.process_before_JSON_Parse(data);

        var tree = null;
        if(ver<SJGNode.VERSION_3){
            tree =new SJGTG();
            tree.fromJson(JSON.parse(data),ver);
        }else{
            tree =new SJGTGV3();
            tree.fromJson(JSON.parse(data),ver);
        }

        // 从提纲树中提取文字[提取root的子对象
        var list = [];
        list.push(id);

        for(var i=0; i<tree.root.children.length; i++){
            var node = tree.root.children[i];
            if(node.kind==SJGNode.SJGNODE_KIND_3  && node.type==SJGNode.SJGNODE_TYPE_1){
                var t = node.value.value;
                t = t.replace(/\n/g,'');
                var topic = node.topic;
                topic = topic.replace(/\n/g,'');
                list.push(topic);
                list.push(t);
            }
        }

        return list.join(',');
    }


    if(from==0){
        // 获取订单文档
        var entity = new TgUserDocModel();
        entity.getOrderUserDoc2(id, function(error, items) {
            if (error || !items || items.length==0) {
                console.log(error);
                return callback(error,null);
            }

            // 提取items中的data中的文字
            var ret = '';
            for(var k=0;k<items.length;k++){
                var one = items[k];
                if(one ){
                    var list = getTexts(one.ver, one.data);
                    if(k>0) ret+='\n'
                    ret += list;
                }
            }

            return callback(null,ret);
        });
    }else if(from==1){
        // 获取订单文档
        var entity = new YjxVideoUserDocModel({
            doc_id:id
        });
        entity.findFromDB( function(error, items) {
            if (error || !items || items.length!=1) {
                console.log(error);
                return callback(error,null);
            }

            // 提取items中的data中的文字
            var one = items[0];
            if(one && one.tg_data){
                var list = getTexts(3, one.tg_data);
                return callback(null, list)
            }

            return callback('无数据',null);
        }, 0, 1);


    }else{
        return callback('无数据',null);
    }

}
//---------------------------------------------------------------------------------
/**
 * 获取"yjsc"上个月的已支付订单中的文字数据
 * 网址：http://120.27.141.121:3000/v5/api4back/getYJSCOrderUserDocTextOfLastMonth
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": "/nas/nas1/yjsc_order_info.csv"
 * }
 */
function getYJSCOrderUserDocTextOfLastMonth(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var outPath = "/nas/nas1/yjsc_order_info.csv";


    /*
    * callback参数：
    *       err:
    *       orderIds:
    * */
    function getOrderIdsOfLastMonth( callback){
        var entity = new ItbTradeOrderModel();
        entity.getLastMonthFinishOrderIds(callback);
    }


    getOrderIdsOfLastMonth(function(err, orderIds){
        if(!orderIds || orderIds.length==0){
            return ret_func(1, CODE.OPERATION_FAILED, {}, res);
        }

        var asyncFuncs = [];
        for (var i=0;i<orderIds.length;i++) {
        //for (var i=0;i<2;i++) {
            //if(i!=149)    continue;
            asyncFuncs.push((function (index, orderId) {
                return function (asyncCallback) {

                    getOrderUserDocTextCore(0, orderId,  function(error, ret){
                        return asyncCallback(error, ret);
                    });

                };
            })(i, orderIds[i])); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            // 将result输出文件
            if(results && results.length>0 ){
                fs.writeFile(outPath, '订单id\n'+results.join('\n'), {flag:'w'} , function(err) {
                    if(err){
                        return ret_func(1, CODE.OPERATION_FAILED, {}, res);
                    }else{
                        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
                    }

                });
            }else{
                return ret_func(1, CODE.OPERATION_FAILED, {}, res);
            }

        });

    });
}
router.get('/getYJSCOrderUserDocTextOfLastMonth', getYJSCOrderUserDocTextOfLastMonth);
router.post('/getYJSCOrderUserDocTextOfLastMonth', getYJSCOrderUserDocTextOfLastMonth);


//---------------------------------------------------------------------------------
/**
 * 获取"yjx"上个月的已支付作品中的文字数据
 * 网址：http://120.27.141.121:3000/v5/api4back/getYJXUserDocTextOfLastMonth
 * 返回值:
 * {
 *   "success": 1,
 *   "msg": "成功",
 *   "data": "/nas/nas1/yjX_order_info.csv"
 * }
 */
function getYJXUserDocTextOfLastMonth(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问

    var outPath = "/nas/nas1/yjx_order_info.csv";


    /*
     * callback参数：
     *       err:
     *       orderIds:
     * */
    function getDocIdsOfLastMonth( callback){
        var entity = new YjxVideoUserDocModel();
        entity.getLastMonthFinishOrderIds(callback);
    }


    getDocIdsOfLastMonth(function(err, docIds){
        if(!docIds || docIds.length==0){
            return ret_func(1, CODE.OPERATION_FAILED, {}, res);
        }

        var asyncFuncs = [];
        //for (var i=0;i<2;i++) {
        for (var i=0;i<docIds.length;i++) {
            //if(i!=149)    continue;
            asyncFuncs.push((function (index, orderId) {
                return function (asyncCallback) {

                    getOrderUserDocTextCore(1, orderId,  function(error, ret){
                        return asyncCallback(error, ret);
                    });

                };
            })(i, docIds[i])); // 利用闭包解决动态参数传递问题
        }
        async.series(asyncFuncs,function (err, results) {
            // 将result输出文件
            if(results && results.length>0 ){
                fs.writeFile(outPath, '文档id\n'+results.join('\n'), {flag:'w'} ,function(err) {
                    if(err){
                        console.log(err);
                        return ret_func(1, CODE.OPERATION_FAILED, {}, res);
                    }else{
                        return ret_func(1, CODE.OPERATION_SUCCESS, {}, res);
                    }

                });
            }else{
                return ret_func(1, CODE.OPERATION_FAILED, {}, res);
            }

        });

    });
}
router.get('/getYJXUserDocTextOfLastMonth', getYJXUserDocTextOfLastMonth);
router.post('/getYJXUserDocTextOfLastMonth', getYJXUserDocTextOfLastMonth);



//===============================================================================================
module.exports = router;